﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Slam
{
	public class SlamActionCollection
	{
		private List<SlamAction> _actionList;
		public SlamActionCollection()
		{
			_actionList = new List<SlamAction>();
		}

		public IEnumerable<SlamAction> GetEventActions(SlamEvent slamEvent)
		{
			return (from a in _actionList
					where a.Event == slamEvent
					let order = a.ExecutionOrder
					orderby order
					select a);
		}

		public void Register(SlamEvent slamEvent, Action<SPListItem> action)
		{
			Register(slamEvent, slamEvent == SlamEvent.PreSave ? Constants.DefaultActionExecutionOrder - 10 : Constants.DefaultActionExecutionOrder + 10, action);
		}

		public void Register(string id, SlamEvent slamEvent, Action<SPListItem> action)
		{
			Register(id, slamEvent, slamEvent == SlamEvent.PreSave ? Constants.DefaultActionExecutionOrder - 10 : Constants.DefaultActionExecutionOrder + 10, action);
		}

		public void Register(SlamEvent slamEvent, int executionOrder, Action<SPListItem> action)
		{
			var slamAction = new SlamAction(action, executionOrder, slamEvent);
			if (!_actionList.Any(a => a.Id.Equals(slamAction.Id, StringComparison.OrdinalIgnoreCase)))
				_actionList.Add(slamAction);
		}

		public void Register(string id, SlamEvent slamEvent, int executionOrder, Action<SPListItem> action)
		{
			Register(id, slamEvent, executionOrder, action, true);
		}

		public void Register(string id, SlamEvent slamEvent, int executionOrder, Action<SPListItem> action, bool synchronous)
		{
			var slamAction = new SlamAction(id, action, executionOrder, slamEvent, synchronous);
			if (!_actionList.Any(a => a.Id.Equals(id, StringComparison.OrdinalIgnoreCase)))
				_actionList.Add(slamAction);
		}
	}
}
